import { defineStore } from 'pinia'
import type { ICartGoods } from '@/types/type'

export const useCartStore = defineStore('cart', {
    state() {
        return {
            list: [] as Array<ICartGoods>,
            stateAll: false,
            orderList:[] as Array<ICartGoods>
        }
    },
    actions: {
        checkAll() {
            this.stateAll = !this.stateAll
            this.list.forEach(item => (item.state = this.stateAll))
        },
        singleCheck(id: number) {
            const goods: ICartGoods | undefined = this.list.find(
                item => item.id === id
            )
            if (goods) {
                goods.state = !goods.state
            }
            this.stateAll = this.list.every(item => item.state)
        },
        // 保存在store里面，购物车里面使用
        saveGoods(goods: ICartGoods) {
            // 相同商品数量加一
            // 判断购物车是否要添加商品如果有则添加数量，如果没有作为新商品添加
            const oldGoods: ICartGoods | undefined = this.list.find(item => item.id === goods.id)
            if (oldGoods) {
                oldGoods.num++
            } else {
                this.stateAll = false//新加商品，全选状态设置为false
                this.list.push(goods)
            }
        },
        deleteGoods(id: number) {
            const index = this.list.findIndex(item => item.id === id)
            this.list.splice(index, 1)
        },
        deleteAllGoods() {
            this.list.splice(0, this.list.length)
        }
    },
    getters: {
        // 总价计算
        totalPrice(): number {
            const sum = this.list.reduce(
                (preventvalue, currentvalue) =>
                    preventvalue +
                    (currentvalue.state
                        ? currentvalue.price * currentvalue.num
                        : 0),
                0
            )
            return Number(sum.toFixed(2)) * 100
        }
        
    },
    persist: {
        enabled: true,//允许存储,默认true
        strategies: [
            {
                key: 'cart',//存储的数据名字
                storage: localStorage,//保存的类型，默认是session,
                paths: ['list', 'stateAll'],//需要持久保存的state里面的数据
            },
        ],
    }
})